home *** CD-ROM | disk | FTP | other *** search
/ CGI How-To / CGI HOW-TO.iso / chap2 / 2_1 / test_env.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-06-15  |  1.9 KB  |  62 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /* function prototype */
  5. char* GetEnv(char *name);
  6.  
  7. main()
  8. {
  9.     /* Send the mime type to the server to expect HTML output */
  10.     printf("Content-type: text/html\n\n");
  11.  
  12.     printf("<HTML>\n");
  13.     printf("<HEAD><TITLE>CGI Script How-to: Test Script</TITLE></HEAD>\n");
  14.     printf("<BODY>\n");
  15.  
  16.     printf("<H1>CGI Environment Variables</H1>\n");
  17.  
  18.     printf("<B>SERVER_SOFTWARE</B> = %s<BR>\n", GetEnv("SERVER_SOFTWARE"));
  19.     printf("<B>SERVER_NAME</B> = %s<BR>\n", GetEnv("SERVER_NAME"));
  20.     printf("<B>SERVER_PORT</B> = %s<BR>\n", GetEnv("SERVER_PORT"));
  21.     printf("<B>GATEWAY_INTERFACE</B> = %s<BR>\n", GetEnv("GATEWAY_INTERFACE"));
  22.     printf("<B>SCRIPT_NAME</B> = %s<BR>\n", GetEnv("SCRIPT_NAME"));
  23.     printf("<B>REMOTE_ADDR</B> = %s<BR>\n", GetEnv("REMOTE_ADDR"));
  24.     printf("<B>REMOTE_HOST</B> = %s<BR>\n", GetEnv("REMOTE_HOST"));
  25.     printf("<B>HTTP_USER_AGENT</B> = %s<BR>\n", GetEnv("HTTP_USER_AGENT"));
  26.     printf("<B>HTTP_ACCEPT</B> = %s<BR>\n", GetEnv("HTTP_ACCEPT"));
  27.  
  28.     printf("</BODY></HTML>\n");
  29.     exit(0);
  30. }
  31.  
  32.  
  33. /* function GetEnv
  34.  *
  35.  * Gets the named environment variable and returns a printable string.
  36.  *
  37.  * Returns: environment value if defined,
  38.  *          otherwise returns an empty string "".
  39.  */
  40.  
  41. char* GetEnv(char *name)
  42. {
  43.     char *value = getenv(name);
  44.  
  45. /* If the environment variable is not defined then getenv would return a NULL
  46.  * or 0, however, if we assume the variable is defined and use this value in
  47.  * a function like strcmp() then the program could abort with a fatal error.
  48.  * Therefore, we don't want to return a NULL string so we check whether getenv
  49.  * returns a NULL string and instead we return an empty string "" if the
  50.  * variable is not defined. Otherwise we return the value returned from getenv
  51.  * like normal. The value returned from GetEnv is therefore safe to use in
  52.  * string comparisons, print statements, and the like.
  53.  */
  54.  
  55.     if (value == NULL) return "";
  56.     else return value;
  57. }
  58.  
  59. /*
  60.  * end of test-env.c
  61.  */
  62.